package redis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author liyanhao
 * @Date 2022-11-25 9:59
 */
@RestController
public class GoodController {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${server.port}")
    private String serverPort;


    @GetMapping("/but_goods")
    public String buy_Goods() {
        String key = "goods:001";
        String result = redisTemplate.opsForValue().get(key);
        int goodsNumber = result == null ? 0 : Integer.valueOf(result);
        if (goodsNumber > 0) {
            int realNumber = goodsNumber - 1;
            redisTemplate.opsForValue().set(key, realNumber + "");
            System.out.println("你已经成功秒杀商品，此时还剩余：" + realNumber + "件 \t 服务器端口号：" + serverPort);
            return "你已经成功秒杀商品，此时还剩余：" + realNumber + "件" + "\t 服务器端口：" + serverPort;
        }else {
            System.out.println("商品已经售罄/活动结束/调用超时，欢迎下次光临"+"\t 服务器端口："+serverPort);
        }
        return "商品已经售罄/活动结束/调用超时，欢迎下次光临"+"\t 服务器端口："+serverPort;
    }

}
